package com.qiaofang.collectmanage.dao.impl;

import com.qiaofang.collectmanage.dao.HouseAgentEsDao;
import com.qiaofang.collectmanage.dao.domain.HouseAgent;
import com.qiaofang.collectmanage.dao.elasticsearch.EsClient;
import com.qiaofang.collectmanage.dao.util.BeanUtils;
import com.qiaofang.collectmanage.dao.util.ConfigUtils;
import com.qiaofang.collectmanage.dao.util.DateUtils;
import com.qiaofang.collectmanage.stub.bean.BatchGetHouseAgentRepeatDTO;
import com.qiaofang.collectmanage.stub.bean.BatchUpdateHouseAgentDTO;
import com.qiaofang.collectmanage.stub.bean.RemoveHouseAgentDTO;
import com.qiaofang.collectmanage.stub.constants.DeletedEnum;
import com.qiaofang.collectmanage.stub.constants.HouseAgentResponseCode;
import com.qiaofang.collectmanage.stub.constants.TableConstants;
import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.util.LogUtil;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

@Repository("houseAgentEsDao")
public class HouseAgentEsDaoImpl implements HouseAgentEsDao {

    private static LogUtil logger = LogUtil.getLogger(HouseAgentEsDaoImpl.class);

    @Override
    public HouseAgent getHouseAgent(HouseAgent getHouseAgent) {
        QueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if (getHouseAgent.getAgentTelephone() != null && !"".equals(getHouseAgent.getAgentTelephone())) {
            ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.termQuery("agentTelephone", getHouseAgent.getAgentTelephone()));
        }
        if (getHouseAgent.getAgentUuid() != null && !"".equals(getHouseAgent.getAgentUuid())) {
            ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.termQuery("agentUuid", getHouseAgent.getAgentUuid()));
        }
        if (getHouseAgent.getDeleted() != null && !"".equals(getHouseAgent.getDeleted())) {
            ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.termQuery("deleted", getHouseAgent.getDeleted()));
        }
        HouseAgent houseAgent = new HouseAgent();
        try {
            SearchResponse searchResponse = EsClient.queryDataSingle(ConfigUtils.getIndexHswhHouseAgent(), TableConstants.INDEX_TYPE_AGENT, queryBuilder);

            if (searchResponse != null) {
                SearchHit[] searchHits = searchResponse.getHits().getHits();
                if (searchHits.length != 0) {
                    SearchHit hit = searchHits[0];
                    Map<String, Object> source = hit.getSource();
                    houseAgent = (HouseAgent) BeanUtils.map2Object(source, HouseAgent.class);
                    houseAgent.setAgentUuid(hit.getId());
                }
            }
        } catch (Exception e) {
            logger.error("getHouseAgent操作es失败{}", e);
            throw new BusinessException(HouseAgentResponseCode.HOUSE_AGENT_GET.getResponseCode(), HouseAgentResponseCode.HOUSE_AGENT_GET.getResponseMessage());
        }
        return houseAgent;
    }

    @Override
    public void deleteIndex(String indexHswhHouseAgent, String indexTypeAgent, RemoveHouseAgentDTO removeHouseAgentDTO) {
        try {
            UpdateRequest updateRequest = new UpdateRequest();
            updateRequest.index(indexHswhHouseAgent);
            updateRequest.type(indexTypeAgent);
            updateRequest.id(removeHouseAgentDTO.getAgentUuid());
            updateRequest.doc(jsonBuilder()
                    .startObject()
                    .field("deleted", DeletedEnum.YES.getValue())
                    .field("updatedTime", removeHouseAgentDTO.getUpdatedTime())
                    .field("updatedUserName", removeHouseAgentDTO.getUpdatedUserName())
                    .endObject());
            EsClient.updateIndex(updateRequest);
        } catch (Exception e) {
            logger.error("updateIndex{}", e);
            throw new BusinessException(HouseAgentResponseCode.HOUSE_AGENT_DELETE.getResponseCode(), HouseAgentResponseCode.HOUSE_AGENT_DELETE.getResponseMessage());
        }
    }

    @Override
    public List<BatchGetHouseAgentRepeatDTO> batchGetHouseAgentRepeatDeletedOrNotDeleted(String index, String type, List<BatchUpdateHouseAgentDTO> batchUpdateHouseAgentDTOs) {
        List<Map<String, Object>> bulkListMap = new ArrayList();
        List<BatchGetHouseAgentRepeatDTO> newBatchUpdateHouseAgentDTOs = new ArrayList<>();
        try {
            QueryBuilder queryBuilder = QueryBuilders.boolQuery();
            List<String> contactMobiles = batchUpdateHouseAgentDTOs.stream().map(BatchUpdateHouseAgentDTO::getAgentTelephone).collect(Collectors.toList());
            if (contactMobiles != null && contactMobiles.size() > 0) {
                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.termsQuery("agentTelephone", contactMobiles));

                SearchResponse searchResponse = EsClient.queryData(index, type, queryBuilder);
                if (searchResponse != null) {
                    SearchHit[] hits = searchResponse.getHits().getHits();
                    for (SearchHit hit : hits) {
                        Map<String, Object> source = hit.getSource();
                        bulkListMap.add(source);
                        BatchGetHouseAgentRepeatDTO newBatchGetHouseAgentDTO = (BatchGetHouseAgentRepeatDTO) BeanUtils.map2Object(source, BatchGetHouseAgentRepeatDTO.class);
                        newBatchUpdateHouseAgentDTOs.add(newBatchGetHouseAgentDTO);
                    }
                }
            }
            return newBatchUpdateHouseAgentDTOs;
        } catch (Exception e) {
            logger.error("批量获取重复的房源中介{}", e);
            throw new BusinessException(HouseAgentResponseCode.HOUSE_AGENT_BATCH_UPDATE_HOUSE_AGENT_TAG.getResponseCode(), HouseAgentResponseCode.HOUSE_AGENT_BATCH_UPDATE_HOUSE_AGENT_TAG.getResponseMessage());
        }
    }

    @Override
    public List<BatchGetHouseAgentRepeatDTO> batchGetHouseAgentRepeat(String index, String type, List<BatchUpdateHouseAgentDTO> batchUpdateHouseAgentDTOs) {
        List<Map<String, Object>> bulkListMap = new ArrayList();
        List<BatchGetHouseAgentRepeatDTO> newBatchUpdateHouseAgentDTOs = new ArrayList<>();
        try {
            QueryBuilder queryBuilder = QueryBuilders.boolQuery();
            List<String> contactMobiles = batchUpdateHouseAgentDTOs.stream().map(BatchUpdateHouseAgentDTO::getAgentTelephone).collect(Collectors.toList());
            if (!contactMobiles.isEmpty()) {
                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.termsQuery("agentTelephone", contactMobiles));

                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.termsQuery("deleted", DeletedEnum.NO.getValue().toString()));

                SearchResponse searchResponse = EsClient.queryData(index, type, queryBuilder);
                if (searchResponse != null) {
                    SearchHit[] hits = searchResponse.getHits().getHits();
                    for (SearchHit hit : hits) {
                        Map<String, Object> source = hit.getSource();
                        bulkListMap.add(source);
                        BatchGetHouseAgentRepeatDTO newBatchGetHouseAgentDTO = (BatchGetHouseAgentRepeatDTO) BeanUtils.map2Object(source, BatchGetHouseAgentRepeatDTO.class);
                        newBatchUpdateHouseAgentDTOs.add(newBatchGetHouseAgentDTO);
                    }

                }
            }
            return newBatchUpdateHouseAgentDTOs;
        } catch (Exception e) {
            logger.error("批量获取重复的房源中介{}", e);
            throw new BusinessException(HouseAgentResponseCode.HOUSE_AGENT_BATCH_UPDATE_HOUSE_AGENT_TAG.getResponseCode(), HouseAgentResponseCode.HOUSE_AGENT_BATCH_UPDATE_HOUSE_AGENT_TAG.getResponseMessage());
        }
    }

    @Override
    public void batchUpdateHouseAgent(String index, String type, List<BatchUpdateHouseAgentDTO> batchUpdateHouseAgentDTOs, int isAgent) {
        List<Map<String, Object>> bulkListMap = new ArrayList();
        try {
            QueryBuilder queryBuilder = QueryBuilders.boolQuery();
            List<String> contactMobiles = batchUpdateHouseAgentDTOs.stream().map(BatchUpdateHouseAgentDTO::getAgentTelephone).collect(Collectors.toList());
            if (!contactMobiles.isEmpty()) {
                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.termsQuery("contactMobile", contactMobiles));
                SearchResponse searchResponse = EsClient.queryDataNoPage(index, type, queryBuilder);
                if (searchResponse != null) {
                    SearchHit[] hits = searchResponse.getHits().getHits();
                    for (SearchHit hit : hits) {
                        Map<String, Object> source = hit.getSource();
                        source.put("id", hit.getId());
                        source.put("isAgent", isAgent);
                        source.put("updateTime", DateUtils.formatDateToZone(new Date()));
                        bulkListMap.add(source);
                    }
                }
                if (!bulkListMap.isEmpty()) {
                    EsClient.bulkUpdateById(index, type, "id", bulkListMap);
                }
            }
        } catch (Exception e) {
            logger.error("batchUpdateHouseAgent批量更新房源中介标识失败{}", e);
            throw new BusinessException(HouseAgentResponseCode.HOUSE_AGENT_BATCH_UPDATE_HOUSE_AGENT_TAG.getResponseCode(), HouseAgentResponseCode.HOUSE_AGENT_BATCH_UPDATE_HOUSE_AGENT_TAG.getResponseMessage());
        }
    }

    @Override
    public void singleUpdateHouseAgent(String index, String type, BatchUpdateHouseAgentDTO batchUpdateHouseAgentDTO, int isAgent) {
        List<Map<String, Object>> bulkListMap = new ArrayList();
        try {
            QueryBuilder queryBuilder = QueryBuilders.boolQuery();

            ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.termsQuery("contactMobile", batchUpdateHouseAgentDTO.getAgentTelephone()));
            SearchResponse searchResponse = EsClient.queryDataNoPage(index, type, queryBuilder);
            if (searchResponse != null) {
                SearchHit[] hits = searchResponse.getHits().getHits();
                for (SearchHit hit : hits) {
                    Map<String, Object> source = hit.getSource();
                    source.put("id", hit.getId());
                    source.put("isAgent", isAgent);
                    bulkListMap.add(source);
                }
                if (!bulkListMap.isEmpty()) {
                    EsClient.bulkUpdateById(index, type, "id", bulkListMap);
                }
            }
        } catch (Exception e) {
            logger.error("singleUpdateHouseAgent批量更新房源中介标识失败{}", e);
            throw new BusinessException(HouseAgentResponseCode.HOUSE_AGENT_BATCH_UPDATE_HOUSE_AGENT_TAG.getResponseCode(), HouseAgentResponseCode.HOUSE_AGENT_BATCH_UPDATE_HOUSE_AGENT_TAG.getResponseMessage());
        }
    }

}
